package com.though.cos.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class CosConfig {

	private static final Logger logger = LoggerFactory.getLogger(CosConfig.class);

	private static final String CONFIG = "/cos-config.properties";

	private static final String CONFIG_TEMPLATE = "/cos-config-template.properties";

	private volatile ConfigParams configParams;

	public CosConfig() {
		init();
	}
	
	public void init() {
		InputStream in = CosConfig.class.getResourceAsStream(CONFIG);
		if (in == null)
        if (in == null) {
            in = CosConfig.class.getResourceAsStream(CONFIG_TEMPLATE);
            if (in == null) throw new RuntimeException("cos-config.properties is not config");
        }
		this.configParams = loadConfgParams(in);
	}

	private ConfigParams loadConfgParams(InputStream in) {
		Properties properties = new Properties();
		try {
			properties.load(in);
			ConfigParams params = new ConfigParams();
			params.setAppId(properties.getProperty("appId"));
			params.setSecretId(properties.getProperty("secretId"));
			params.setSecretKey(properties.getProperty("secretKey"));
			params.setBucketName(properties.getProperty("bucketName"));
			return params;
			
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error("Error:close oss propertis file", e);
				}
			}
		}
	}

	public ConfigParams getConfigParams() {
		return configParams;
	}
}
